const Router = require('koa-router')
const debug = require('debug')('login')
// 引入db.js
const db = require('../../servse/db.js')

const router = new Router()

router.get('/', async (ctx, next) => {
  await ctx.render('login')
})

router.post('/doLogin', async (ctx, next) => {
  const name = ctx.request.body.username
  const psd = ctx.request.body.password
  const result = await db.findAdmin(name, psd)
  debug('admininfo: ', result[0])
  // const adminuser = resultInfo[0]
  // // 验证密码
  // const result = await bcrypt.compareSync(ctx.request.body.password, adminuser.password)
  if (result) {
    try {
      ctx.session.userInfo = result[0]
      return ctx.redirect('/admin/index/main')
    } catch (e) {
      ctx.body = { status: 200, msg: 'session设置失败', err: e }
      return ctx.body
    }
  }
  return ctx.redirect('/admin/login')
})

router.get('/loginout', async (ctx, next) => {
  if (ctx.session.userInfo) {
    ctx.session = null
  }
  return ctx.redirect('/admin/login')
})

module.exports = router.routes()
